package hengtiansoft.com.myapplication.game;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import hengtiansoft.com.myapplication.BaseActivity;

public class TestGameActivity extends BaseActivity {
    boolean isLow;

    Random random = new Random();
    int ballx = random.nextInt(200 + 20);
    int bally = random.nextInt(10 + 20);
    int BallSize = 15;
    final int RACKET_HEIGHT = 20;
    final int RACKET_WIDTH = 70;
    int rectx = random.nextInt(200);
    int recty;
    int ySpeed = 20;
    double xyRate = random.nextDouble() - 0.5;//
    int xSpeed = (int) (ySpeed * xyRate * 2);

    Button left, right;
    int tableWidth;
    int tableHeight;
    final Timer timer = new Timer();

    @Override
    public void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        final GameView gameView = new GameView(this);
        setContentView(gameView);
        //获取窗口管理器
        final WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        final DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        tableWidth = metrics.widthPixels;
        tableHeight = metrics.heightPixels;
        android.view.WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        left = new Button(this);
        left.setText("Left");
        left.setTextColor(Color.RED);
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rectx > 0) rectx -= 10;
            }
        });
//        windowManager.addView(left, lp);
        recty = tableHeight - 80;
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0) {
                    gameView.invalidate();
                }
                super.handleMessage(msg);
            }
        };
        gameView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, final MotionEvent event) {//获取点击位置坐标,移动柱子
                Log.e("event", event.toString());
                if (event.getX() < tableWidth / 2 &&event.getAction() == MotionEvent.ACTION_DOWN) {
                            if (rectx > 0) rectx -= 15;
                        } else {
                            if (rectx < tableWidth - RACKET_WIDTH) rectx += 15;
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                }

                return false;
            }
        });
        gameView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                switch (event.getKeyCode()) {
                    //左移
                    case KeyEvent.KEYCODE_VOLUME_DOWN:
                        if (rectx < tableWidth - RACKET_WIDTH) rectx += 15;
                        break;
                    case KeyEvent.KEYCODE_VOLUME_UP://右移
                        if (rectx > 0) rectx -= 15;
                        break;
                    case KeyEvent.KEYCODE_BACK:
                        closeFlash();
                        TestGameActivity.this.finish();
                        break;
                }
                gameView.invalidate();
                return true;//确认事件被消费,不再往后面传递,否则会调整系统的音量;
            }
        });
        gameView.setFocusable(true);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //简单讲就是当球撞到墙时,反向运动
                if (ballx <= 0 || ballx >= tableWidth - BallSize) {//在左边框
                    xSpeed = -xSpeed;
                }
                //如果球撞到地上了就失败了 否则就反向运动
                if (bally >= recty - BallSize && (ballx < rectx || ballx > rectx + RACKET_WIDTH)) {
                    timer.cancel();
                    isLow = true;
                    openFlashlight();
                } else if (bally <= 0 || bally >= recty - BallSize
                        && ballx > rectx && ballx <= rectx + RACKET_WIDTH) {
                    ySpeed = -ySpeed+random.nextInt(5);
                }
                bally += ySpeed;
                ballx += xSpeed;
                handler.sendEmptyMessage(0);
            }
        }, 0, 100);
    }

    @Override
    public void initData() {

    }

    class GameView extends View {

        Paint paint = new Paint();

        public GameView(Context context) {
            super(context);
            setFocusable(true);//不获取焦点
            setFocusableInTouchMode(true);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);
            if (isLow) {
                paint.setColor(Color.RED);
                paint.setTextSize(30);
                canvas.drawText("GameOver", 50, 200, paint);

            } else {
                paint.setColor(Color.YELLOW);
                //画圆
                canvas.drawCircle(ballx, bally, BallSize, paint);
                paint.setColor(Color.rgb(80, 80, 200));
                //画矩形
                canvas.drawRect(rectx, recty, rectx + RACKET_WIDTH, recty + RACKET_HEIGHT, paint);
                paint.setColor(Color.RED);
//                canvas.drawRect(0, tableWidth / 2, 80, 50, paint);
                paint.setTextSize(30);
                canvas.drawText("Left", 0, tableHeight / 2, paint);
                canvas.drawText("Right", tableWidth - 80, tableHeight / 2, paint);

            }

            super.onDraw(canvas);
        }

    }

    @Override
    protected void onDestroy() {
        timer.cancel();
        closeFlash();
        super.onDestroy();
    }

    Camera mCamera;
    Camera.Parameters mParameters;

    // 打开闪光灯
    void openFlashlight() {
        try {
            mCamera = Camera.open();
            int textureId = 0;
            mCamera.setPreviewTexture(new SurfaceTexture(textureId));
            mCamera.startPreview();

            mParameters = mCamera.getParameters();

            mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            mCamera.setParameters(mParameters);

        } catch (Exception e) {
            // TODO: handle exception
            Log.e("Flash", e.toString());
        }
    }

    void closeFlash() {
        if (mCamera != null) {
            mParameters = mCamera.getParameters();

            mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);// 关闭

            mCamera.setParameters(mParameters);

            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;

        }
    }


}
